<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use  Think\DB;

class JiangpinController extends BaseController {
	protected function _initialize() {
		parent::_initialize();
	}
	//兑换奖品
	public function ex_jp(){
		$user_info=session('user_info');
		if(!$user_info){
			return json(['code'=>400,'msg'=>'领取失败']);
		}
		$jp=db('action_prize')->where("id",input("id"))->find();
		$num=$jp['num'];
		$logs=db('prizelogs')->where("prize_id",input("id"))->count();
		if($logs&&$logs>=$num){
			return json(['code'=>400,'msg'=>'兑换失败奖品剩余数量为0']);
		}else{
			Db::startTrans();
			$items=explode(",", $jp['demand']);
			$w['user_id']=$user_info['id'];
			$w['nums']=[">=",1];
			foreach($items as $k=>$v){
				$w['item_id']=$v;
				$res=db("user_items")->where($w)->setDec("nums",1);
				if(!$res){
					 Db::rollback();
					return json(['code'=>400,'msg'=>'矿石数量不足兑换失败']);
				}
			}
			$data['user_id']=$user_info['id'];
			$data['prize_id']=input("id");
			$data['add_time']=now_time();
			$data['mobile']=$user_info['mobile'];
			$res=db("prizelogs")->insert($data);
			if(!$res){
				Db::rollback();
					return json(['code'=>400,'msg'=>'兑换失败']);
			}else{
				Db::commit();
				return json(['code'=>200,'msg'=>'兑换成功']);
			}
		}
		
	}
	//随机抽奖矿石
	public function lingqu(){
		$user_id=session("user_info")['id'];
		if(!$user_id){
			echo '用户未注册领取失败';exit;
		}
		$agent_id=input('agent_id');
		$jps=db("action_prize")->select();
		$items=db("action_item")->where("state",1)->field('id,thumb,name,probability')->select();
		$list=array();
		$list1=array();
		foreach($items as $k=>$v){
			$list1[$v['id']]=$v;
			$list[$v['id']]=$v['probability'];
		}
		$rid = get_rand($list); //根据概率获取奖项id
		$item=$list1[$rid];
		$w['user_id']=$user_id;
		$w['agent_id']=$agent_id;
		$logs=db("action_log")->where($w)->wheretime("add_time","today")->select();
		if($logs&&count($logs)>=2){
			return $this->fetch("lingqu_sb");
		}else{
			$wh['user_id']=$user_id;
			$wh['item_id']=$rid;
			$lq=db('user_items')->where($wh)->find();
			$data['user_id']=$user_id;
			$data['item_id']=$rid;
			if($lq){
				db("user_items")->where($wh)->setInc("nums",1);
			}else{
				db("user_items")->insert($data);
			}
			$data['add_time']=now_time();
			$data['agent_id']=$agent_id;
			$res=db('action_log')->insert($data);
		}
		
		$this->assign('item',$item);
		return $this->fetch("lingqu_cg");
	}
	public function lingqu_cg(){
		return $this->fetch();
	}
	public function lingqu_sb(){
		return $this->fetch();
	}
}